<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <!-- <el-option value="externalOrderCode" label="外部订单号" /> -->
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <!-- <el-option value="externalCsmCode" label="外部客户编号" /> -->
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <!-- <el-option value="transactor" label="下单人" />
          <el-option value="remark" label="备注" />
          <el-option value="goodsDesc" label="商品描述" />
          <el-option value="ownerName" label="处理人" />
          <el-option value="saleMan" label="销售员" /> -->
          <el-option value="sfzh" label="身份证号" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="下单时间" value="transactTime" />
          <el-option label="退单时间" value="refundTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          unlink-panels
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select
          v-model="user_qtype"
          style="width: 170px; margin-right: 2px;"
          @change="qtypeChange"
        >
          <el-option value="ownerIdList" label="处理人" />
          <el-option value="transactIdList" label="下单人" />
        </el-select>
        <el-select
          v-model="user_qtype_value"
          :loading="$loadingPlugin.getOwnerList || $loadingPlugin.getTransactorList"
          filterable
          clearable
          multiple
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in userQtypeList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="超时状态:">
        <el-select v-model="query.overTimeType" clearable>
          <el-option label="超时预警" :value="1" />
          <el-option label="已超时" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[40108, 1]"
          :loading="$loadingPlugin.fetchData"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="[40108, 2]"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile(0)"
        >导出</el-button>
        <!-- <el-button v-permission="[40101, 12]" type="primary" icon="el-icon-download" @click="exportFile(1)">非脱敏导出</el-button> -->
      </div>
    </div>
    <div class="table_Main">
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        class="orderList"
        height="250"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        :row-class-name="tableRowClassName"
        custom-column
        default-open
        @fetch="fetchData"
      />
      <div class="total">本页商品总计:{{ goodsCount }} </div>
    </div>
    <csm-location ref="csmLocation" />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymentMethodMap" :parent-fetch-data="search" />
    <order-images ref="orderImages" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <pay-detail ref="payDetail" :payment-method-map="paymentMethodMap" />
    <species-amount ref="speciesAmount" />
    <press-order-report ref="pressOrderReport" />
    <warnInfo ref="warnInfo" />
  </div>
</template>

    <script>
  import {
    querySubTypeMap,
    queryTransactorList,
    queryRefundList,
    queryMap,
    queryRefundListExport,
    queryExportDomain,
    batchOrderBatchDetail,
    queryCsmInfo,
    queryRiskTrackMap,
    orderbillRecord,
    csDeliverUserList
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { payStatusObj } from '@/utils/map'
  import CsmLocation from '../../../components/CsmLocation'
  import OrderImages from './OrderImages'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import OrderDetail from './OrderDetails'
  import PayDetail from './PayDetail'
  import SpeciesAmount from './SpeciesAmount'
  import PressOrderReport from '../../../components/PressOrderReport'
  import warnInfo from '../../../customerCenter/customerManage/components/WarnInfo'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { toRMB } from '@/filters'
  import ownBottle from '@/assets/ownBottle.png'

  export default {
    components: {
      PressOrderReport,
      CsmLocation,
      OrderImages,
      CsmDetail,
      OrderDetail,
      PayDetail,
      SpeciesAmount,
      warnInfo
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return moment(time.getTime()).diff(moment(Date.now()), 'days') < 0
          }
        },
        actionColWidth: 80,
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        orderSourceMap: [],
        orderFlagMap: [],
        user_qtype: 'ownerIdList',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'transactTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        date1: parseTime(Date.now(), '{y}-{m}-{d}'),
        orderStatusMap: [],
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        calcTypeList: [],
        searchParams: {},
        warnLevelMap: [],
        subTypeList: [],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          overTimeType: ''
        },
        backAttributeList: [
          { desc: '全部', value: '' },
          { desc: '安全原因', value: 1 },
          { desc: '非安全原因', value: 2 }
        ],
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        },
        goodsCount: 0,
        deliveryTypeMap: [{ desc: '大车用户', value: 1 }, { desc: '电子围栏用户', value: 2 }]
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          // {
          //   prop: 'imageUrl',
          //   label: '图片',
          //   width: 50,
          //   align: 'center',
          //   render: (h, { row }) => {
          //     if (((row.intSpare6 >> 7) & 0x01) > 0) {
          //       return (
          //       <span
          //         onClick={() => this.showImage(row)}
          //         style='color:green;cursor:pointer;'
          //       >
          //         <i class='el-icon-picture' />
          //       </span>
          //       )
          //     } else {
          //       return ''
          //     }
          //   }
          // },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            className: 'orderCodeClass',
            fixed: 'left',
            render: (h, { row }) =>
              (row.isFreeBottle === 1 || row.isFreeBottle === 2) ? (
            <div class='checkImg'>
            <img src={ ownBottle} alt={''}/>
            <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
              {row.orderCode}
            </el-link>
              </div>
                ) : (
                  <div class='link'>
                    <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
              {row.orderCode}
            </el-link>
                  </div>

          )
          },
          {
            prop: 'transactor',
            label: '下单人',
            showOverflowTooltip: true
          },
          {
            prop: 'ownerName',
            label: '处理人',
            showOverflowTooltip: true
          },
          {
            prop: 'driverName',
            label: '大车司机',
            showOverflowTooltip: true
          },
          {
            prop: 'escortName',
            label: '押运员',
            showOverflowTooltip: true
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 220,
            render: (h, { row }) => {
              return (
              <span>
                <span class='point-span'>
                  {this.$btnPermission([40101, 10]) && row.lon && row.lat && (
                    <i
                      onClick={() => this.openLocation(row)}
                      class='linkColor el-icon-location'
                      style='cursor: pointer;'
                    />
                  )}
                  {!this.$btnPermission([40101, 10]) && (
                    <i class='el-icon-location' style='color:#126edc;cursor: pointer;' />
                  )}
                </span>
                <span>{row.csmAddress}</span>
              </span>
              )
            }
          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
              {row.csmName}
            </el-link>
          )
          },
          {
            prop: 'warnLevel',
            label: '隐患等级',
            render: (h, { row }) =>
              row.warnLevel ? (
              <el-link underline={false} onClick={() => this.warnInfo(row)}>
                {formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}
              </el-link>
                ) : (
              <span>无隐患</span>
            )
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 130,
            render: (h, { row }) => {
              if (row.contactPhone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.contactPhone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'transactTime',
            label: '下单时间',
            width: 140,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(1, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(1, 2)}></i></span>
            },
            render: (h, { row }) => (
            <span>
              {row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'overTimeType',
            label: '超时状态',
            width: 100,
            render: (h, { row }) => (
            <span class={row.overTimeType === 1 ? 'yellow' : 'red'} onClick={() => this.showTimeoutDetails(row)}>
              {row.overTimeType === 1 ? '超时预警' : row.overTimeType === 2 ? '已超时' : ''}
            </span>
            )
          },
          {
            prop: 'appointmentDt',
            label: '预约时间',
            minWidth: 200,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(2, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(2, 2)}></i></span>
            },
            render: (h, { row }) => {
              return (
                <div class={this.getClass(row)}>
                  {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                </div>
              )
            }
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => (
            <span>
              {row.csmType &&
                formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc')}
            </span>
          )
          },
          {
            prop: 'subType',
            label: '用气性质',
            minWidth: 110,
            render: (h, { row }) => (
            <span>
              {row.subType ? formatColumnMap(this.subTypeAllList, 'value', row.subType, 'label') : ''}
            </span>
          )
          },
          {
            prop: 'urgeCount',
            label: '催单次数',
            render: (h, { row }) =>
              row.urgeCount ? (
              <el-link underline={false} onClick={() => this.openPressOrderReport(row)}>
                {row.urgeCount}
              </el-link>
                ) : (
              <span>{row.urgeCount}</span>
            )
          },
          {
            prop: 'refundPropertyType',
            label: '退单属性',
            render: (h, { row }) => <span>{ row.refundPropertyType ? formatColumnMap(this.backAttributeList, 'value', row.refundPropertyType, 'desc') : '' }</span>

          },
          {
            prop: 'backReason',
            label: '退单理由',
            width: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'refundReason',
            label: '退单原因',
            render: (h, { row }) => <span>{ row.refundReason}</span>
          },
          {
            prop: 'refundTime',
            label: '退单时间',
            width: 150,
            render: (h, { row }) => (
                <span>
                  {row.refundTime && parseTime(row.refundTime, '{y}-{m}-{d} {h}:{i}')}
                </span>
              )
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'fromPlat',
            label: '订单来源',
            render: (h, { row }) => (
            <span>
              {row.fromPlat &&
                formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc')}
            </span>
          )
          },
          {
            prop: 'csmPhone',
            label: '呼入电话',
            width: 130,
            render: (h, { row }) => {
              if (row.csmPhone) {
                return (
                  <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.csmPhone}
                </span>
                )
              }
              return ''
            }
          },
          {
            prop: 'contact',
            label: '联系人'
          },
          {
            prop: 'goodsCount',
            label: '商品总数',
            align: 'right'
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },
          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.decimalSpare4 && row.decimalSpare4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'decimalSpare1',
            label: '总远距配送费',
            align: 'right',
            width: 110,
            render: (h, { row }) => (
            <span>{row.decimalSpare1 && row.decimalSpare1.toFixed(2)}</span>
          )
          },
          {
            prop: 'distance',
            label: '配送距离(km)',
            align: 'center',
            width: 110,
            render: (h, { row }) => (
            <span>{row.distance && (row.distance / 1000).toFixed(2)}</span>
          )
          },
          {
            prop: 'decimalSpare2',
            label: '总上楼费',
            align: 'right',
            render: (h, { row }) => (
            <span>{row.decimalSpare2 && row.decimalSpare2.toFixed(2)}</span>
          )
          },
          {
            prop: 'decimalSpare3',
            label: '总服务费',
            align: 'right',
            render: (h, { row }) => (
            <span>{row.decimalSpare3 && row.decimalSpare3.toFixed(2)}</span>
          )
          },
          {
            prop: 'totalFee4',
            label: '优惠金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openSpeciesAmount(row)}>
              {row.totalFee4 && row.totalFee4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'treceivables',
            label: '应收金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.treceivables}
            </el-link>
          )
          },
          {
            prop: 'taccReceivable',
            label: '实收金额',
            align: 'right',
            render: (h, { row }) => (
              row.payStatus !== 1 && <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.taccReceivable && row.taccReceivable.toFixed(2)}
            </el-link>
            )
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => (
            <span style={payStatusObj[row.payStatus]}>
              {row.payStatus
                ? formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc')
                : '未支付'}
            </span>
          )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          },
          {
            prop: 'isPickUp',
            label: '自提',
            align: 'center',
            width: 70,
            render: (h, { row }) =>
              row.isPickUp && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            prop: 'dateTimeSpare2',
            label: '上次安检时间',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.dateTimeSpare2 && parseTime(row.dateTimeSpare2, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          }
        ]
      }
    },
    watch: {
    },
    async created() {
      const res1 = await querySubTypeMap({ })
      this.subTypeAllList = res1.data
      this.subTypeList = this.subTypeAllList
      await Promise.all([
        this.getExportDomain(),
        this.getTreeData(),
        // this.getTransactorList(),
        // this.getOwnerList(),
        this.queryOptionsMap(),
        this.getdanger(),
        this.qtypeChange('ownerId')
      ])
    },
    methods: {
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      sortColumn(sortColumn, sortType) {
        this.query.sortColumn = sortColumn
        this.query.sortType = sortType
        this.search()
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        query[this.user_qtype] = this.user_qtype_value
        if (this.date && this.date.length === 2) {
          if (this.dateType !== 'appointmentDt') {
            query[this.dateType] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            query[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        if (this.dateType === 'appointmentDt' && this.date1) {
          query.appointmentDt = moment(this.date1).format('YYYY-MM-DD') + ' 00:00:00'
          query.dateTimeSpare1 = moment(this.date1).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const res = await queryRefundList(query)
        if (res.data) {
          this.searchParams = query
          this.tableData.data = res.data.rows
          if (currentPage === 1) this.tableData.total = res.data.total
          this.goodsCount = 0
          for (const i in this.tableData.data) {
            var item = this.tableData.data[i]
            this.goodsCount += item.goodsCount
          }
        }

        this.flexColumnWidth()
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 清空所属机构
      closeTree(v) {
        if (this.user_qtype === 'ownerIdList') {
          this.user_qtype_value = []
          this.userQtypeList = []
        }
        this.currentOrg = undefined
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 4 && item.value !== 6 && item.value !== 8) // 订单类型(去掉‘已转派’“已接收”“已出库”)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        // console.log(this.customerTypeMap)
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 1024 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
        this.calcTypeList = res8.data // 收款方式
        console.log('this.orderStatusMap', this.orderStatusMap)
      },
      async getdanger() {
        const res = await queryRiskTrackMap()
        const data = JSON.parse(res.data.warnLevel) // 隐患等级
        if (data) {
          this.warnLevelMap = []
          data.forEach(item => {
            this.warnLevelMap.push({
              value: item.keyVal,
              desc: item.keyName
            })
          })
        }
      },
      // 配送距离数据格式化
      distanceFormat(v, r, i) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      // 获取处理人列表
      async getOwnerList() {
        const orgId = this.currentOrg ? this.currentOrg.orgId : 0
        const orgSNNo = this.currentOrg ? this.currentOrg.orgSNNo : 0
        if (orgId) {
          const res = await csDeliverUserList({
            deliveryOrgId: orgId,
            deliveryOrgSNNo: orgSNNo
          })
          this.ownerList = res.data
        } else {
          this.ownerList = []
        }
        if (this.user_qtype === 'ownerIdList') {
          this.user_qtype_value = []
          this.userQtypeList = this.ownerList
        } else {
          this.userQtypeList = this.transactorList
        }
      },
      // 获取下单人列表
      async getTransactorList() {
        if (this.transactorList.length === 0) {
          const res = await queryTransactorList({})
          this.transactorList = res.data
        }
        if (this.user_qtype === 'ownerIdList') {
          this.userQtypeList = this.ownerList
        } else {
          this.userQtypeList = this.transactorList
        }
      },
      // 隐患详情
      warnInfo(row) {
        this.$refs.warnInfo.open(row)
      },
      // 处理人或下单人选择
      async qtypeChange(value) {
        this.user_qtype_value = []
        if (value === 'ownerIdList') {
          await this.getOwnerList()
        } else {
          await this.getTransactorList()
        }
      },
      // 点击催单次数
      async openPressOrderReport(row) {
        await this.$refs.pressOrderReport.open({ billCode: row.orderCode, billType: 1 })
      },
      // 点击图片
      async showImage(row) {
        await this.$refs.orderImages.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
        this.search()
      },
      // 点击订单总额
      async openPayDetail(row) {
        await this.$refs.payDetail.open(row)
      },
      // 点击优惠金额
      async openSpeciesAmount(row) {
        await this.$refs.speciesAmount.open(row)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile(type) {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.splice(4, 0, { label: '开户人', prop: 'openUser' })
          copyColumn.splice(5, 0, { label: '配送员编号', prop: 'ownerCode' })
          copyColumn.splice(6, 0, { label: '配送员身份证', prop: 'ownerCard' })
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          if (this.date && this.date.length === 2) {
            params[this.dateType] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            params[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          } else {
            params.appointmentDt = moment(this.date1).format('YYYY-MM-DD HH:mm:ss')
            params.dateTimeSpare1 = moment(this.date1).format('YYYY-MM-DD HH:mm:ss')
          }
          params.tabType = 1
          params.desensitizeFlag = type
          queryRefundListExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7 || row.orderStatus === 3) {
          // 7:已退单 3:退单申请中
          return 'danger-row'
        }
        if (row.orderStatus === 9 || row.orderStatus === 12) {
          // 9:退货申请中 12:已退货
          return 'giveup-row'
        }
        return ''
      },
      async tryPrint(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await batchOrderBatchDetail(params)
        if (status === 200) {
          this.tryPrint2(row)
          this.tryPrint1(row, data)
        }
      },
      async tryPrint1(row, items) {
        const params = {
          csmId: row.csmId
        }
        const { status, data } = await queryCsmInfo(params)
        if (status === 200) {
          row['lastBuyDt'] = data['lastBuyDt'] || ''
          row['score'] = data['score'] || 0
          this.print(row, items)
        }
      },
      async tryPrint2(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await orderbillRecord(params)
        if (status === 200) {
          row['fee1'] = data['fee1'] || 0
          row['fee2'] = data['fee2'] | 0
          row['preferentialPackageName'] = data['preferentialPackageName'] || ''
          row['preferentialCount'] = data['preferentialCount'] || 0
          // 预约时间
          var reservationDt = ''
          var day = parseTime(row.appointmentDt || row.dateTimeSpare1, '{y}-{m}-{d} ')
          if (row.appointmentDt && !row.dateTimeSpare1) {
            const time1 = parseTime(row.appointmentDt, '{h}:{i}')
            reservationDt = String.format('{0}{1}之后', day, time1)
          } else if (!row.appointmentDt && row.dateTimeSpare1) {
            const time2 = parseTime(row.dateTimeSpare1, '{h}:{i}')
            reservationDt = String.format('{0}{1}之前', day, time2)
          } else {
            const time1 = parseTime(row.appointmentDt, '{h}:{i}')
            const time2 = parseTime(row.dateTimeSpare1, '{h}:{i}')
            reservationDt = String.format('{0}{1}至{2}', day, time1, time2)
          }
          row.reservationDt = reservationDt
        }
        return row
      },
      print(row2, items) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['38']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        row.printDt = parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')
        // row.dateTimeSpare2 = dayjs(row.dateTimeSpare2).format('YYYY-MM-DD hh:mm')
        row.printMoney = `${row.treceivables}(${toRMB(row.treceivables)})`
        row.payMethod = ''
        if (row.fromPlat !== 1 && row.fromPlat !== 7) {
          for (var item in this.paymentMethodMap) {
            if ((item && row.paymentMethod) > 0) {
              row.payMethod += this.paymentMethodMap[item].desc + ','
            }
          }
          row.payMethod = (row.payMethod || '').replace(/(^,+)|(,+$)/g, '')
        }
        for (var i in items) {
          const item = items[i]
          item.goodsTotalPrice = this.toDecimal(item.gcount * item.gprince, 2).toFixed(2)
          item.gprince = this.toDecimal(item.gprince, 2).toFixed(2)
          item.fee1 = this.toDecimal(item.fee1, 2).toFixed(2)
          item.fee2 = this.toDecimal(item.fee2, 2).toFixed(2)
        }
        if (row.payStatus === 3) {
          row.printMoney = `${row.printMoney} 已支付(${formatColumnMap(
            this.paymentMethod,
            'value',
            row.payMethod,
            'desc'
          )})`
        } else {
          row.taccReceivable = ''
        }
        row.csmAddress = row.csmAddress.includes('市') ? row.csmAddress.replace(/市/, ' ').split(' ')[1] : row.csmAddress
        // row.csmTypeName = this.customerTypeMap[row.csmType] || '居民用户'
        row.csmTypeName =
          formatColumnMap(this.customerType, 'value', row.csmType, 'desc') || '居民用户'
        row.goodsDesc = row.goodsDesc.split('^')[0]
        if (items.length > 0) {
          row.price = items[0].gprince
        }
        if (row.isPickUp === 1) {
          row.orgNewName = row.orgName + '零售单(自提)'
        } else {
          row.orgNewName = row.orgName + '零售单'
        }
        if (row.preferentialCount === 0) {
          row.preferentialCount = ''
        }
        row.treceivables = this.toDecimal(row.treceivables, 2).toFixed(2)
        row.fee1 = this.toDecimal(row.fee1 / 100, 2).toFixed(2)
        row.fee2 = this.toDecimal(row.fee2 / 100, 2).toFixed(2)
        if (row.fee1 === 0) {
          row.fee1 = ''
        }
        if (row.fee2 === 0) {
          row.fee2 = ''
        }
        if (row.ownerName === null || row.ownerName === undefined) {
          row.ownerName = ''
        }
        if (row.remark === null || row.remark === undefined) {
          row.remark = ''
        }
        if (row.preferentialPackageName === null || row.preferentialPackageName === undefined) {
          row.preferentialPackageName = ''
        }
        let printcmd = {
          cmd: 2,
          title: `正在对订单${row.orderCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        window.jCPrint.process(printcmd, temp, row, items)
        delete printcmd.els
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      },
      toDecimal(str, p) {
        var reg = /^(-?\d+)(\.\d+)?$/
        if (reg.test(str)) {
          return parseFloat(str).toFixed(p || 2) * 1
        }
        return 0
      },
      async showTimeoutDetails(row) {
        this.$refs.orderDetail.open(row, 'overTime')
      }
    }
  }
</script>

<style lang="scss" scoped>
.table_Main {
  position: relative;
  .total {
    position: absolute;
    right: 5px;
    bottom: 5px;
    font-size: 16px;
    font-weight: 500;
    // color: #F00;
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffeced;
}
/deep/ .el-table tr.giveup-row {
  background: #ffeced;
}
/deep/.red {
  color: #f00 !important;
  cursor: pointer;
}
/deep/.yellow {
  color: #ed912e !important;
  cursor: pointer;
}

.orderList {
  & /deep/ .el-table .orderCodeClass {
    padding: 0;
    // .cell {
    //   padding: 0;
    // }
    .checkImg {
      display: flex;
      margin-left: -9px;
      img {
        width: 30px;
        height: auto;
      }
    }
    // .link {
    //   padding: 0 10px;
    // }
  }
}
</style>
